/**
 * 统计控制器
 * 提供各种数据分析和统计功能
 */

const logger = require('../../logger');
const AdminUser = require('../models/adminUser.model');
const User = require('../../models/User'); // 正确的用户模型路径

/**
 * 获取系统总览统计数据
 */
async function getOverviewStats(req, res) {
    try {
        logger.info('获取系统总览统计数据');
        
        // 模拟统计数据
        const stats = {
            totalUsers: 1258,
            activeUsers: 456,
            newUsersToday: 34,
            totalAdmins: 8,
            contentCount: {
                horoscope: 365,
                tarot: 120,
                dream: 250,
                faceReading: 89,
                palmReading: 76
            },
            systemStatus: 'normal',
            lastBackupTime: '2024-05-01T10:30:00Z'
        };
        
        res.status(200).json({
            success: true,
            data: stats,
            message: '获取系统总览统计成功'
        });
    } catch (error) {
        logger.error('获取系统总览统计失败', error);
        res.status(500).json({
            success: false,
            message: '获取统计数据失败',
            error: error.message
        });
    }
}

/**
 * 获取用户增长趋势数据
 */
async function getUserGrowthStats(req, res) {
    try {
        const { period = 'week' } = req.query;
        logger.info(`获取用户增长趋势数据，周期: ${period}`);
        
        // 模拟用户增长数据
        let growthData = [];
        
        if (period === 'week') {
            growthData = [
                { date: '2024-04-25', newUsers: 42, activeUsers: 320 },
                { date: '2024-04-26', newUsers: 38, activeUsers: 315 },
                { date: '2024-04-27', newUsers: 56, activeUsers: 340 },
                { date: '2024-04-28', newUsers: 67, activeUsers: 380 },
                { date: '2024-04-29', newUsers: 75, activeUsers: 420 },
                { date: '2024-04-30', newUsers: 82, activeUsers: 450 },
                { date: '2024-05-01', newUsers: 34, activeUsers: 456 }
            ];
        } else if (period === 'month') {
            growthData = [
                { date: '2024-04-01', newUsers: 120, activeUsers: 280 },
                { date: '2024-04-05', newUsers: 135, activeUsers: 295 },
                { date: '2024-04-10', newUsers: 148, activeUsers: 310 },
                { date: '2024-04-15', newUsers: 162, activeUsers: 330 },
                { date: '2024-04-20', newUsers: 178, activeUsers: 360 },
                { date: '2024-04-25', newUsers: 195, activeUsers: 380 },
                { date: '2024-05-01', newUsers: 210, activeUsers: 420 }
            ];
        }
        
        res.status(200).json({
            success: true,
            data: growthData,
            message: '获取用户增长趋势成功'
        });
    } catch (error) {
        logger.error('获取用户增长趋势失败', error);
        res.status(500).json({
            success: false,
            message: '获取用户增长数据失败',
            error: error.message
        });
    }
}

/**
 * 获取内容使用统计数据
 */
async function getContentUsageStats(req, res) {
    try {
        logger.info('获取内容使用统计数据');
        
        // 模拟内容使用统计
        const usageStats = {
            contentTypes: [
                { type: 'horoscope', views: 12540, favorites: 3245, rating: 4.5 },
                { type: 'tarot', views: 8930, favorites: 2134, rating: 4.7 },
                { type: 'dream', views: 6780, favorites: 1876, rating: 4.3 },
                { type: 'faceReading', views: 4520, favorites: 987, rating: 4.6 },
                { type: 'palmReading', views: 3890, favorites: 765, rating: 4.4 }
            ],
            popularTags: [
                { tag: '财运', count: 456 },
                { tag: '爱情', count: 389 },
                { tag: '事业', count: 324 },
                { tag: '健康', count: 215 },
                { tag: '婚姻', count: 198 }
            ],
            peakHours: [
                { hour: '9-10', usage: 120 },
                { hour: '12-13', usage: 180 },
                { hour: '18-19', usage: 250 },
                { hour: '20-21', usage: 320 },
                { hour: '21-22', usage: 280 }
            ]
        };
        
        res.status(200).json({
            success: true,
            data: usageStats,
            message: '获取内容使用统计成功'
        });
    } catch (error) {
        logger.error('获取内容使用统计失败', error);
        res.status(500).json({
            success: false,
            message: '获取内容使用统计失败',
            error: error.message
        });
    }
}

/**
 * 获取API性能统计数据
 */
async function getApiPerformanceStats(req, res) {
    try {
        const { timeRange = 'day' } = req.query;
        logger.info(`获取API性能统计数据，时间范围: ${timeRange}`);
        
        // 模拟API性能数据
        const performanceData = {
            endpointStats: [
                { endpoint: '/api/horoscope/daily', avgResponseTime: 120, errorRate: 0.5, requestCount: 4567 },
                { endpoint: '/api/tarot/read', avgResponseTime: 230, errorRate: 0.3, requestCount: 2345 },
                { endpoint: '/api/dream/interpret', avgResponseTime: 180, errorRate: 0.7, requestCount: 1890 },
                { endpoint: '/api/face/analyze', avgResponseTime: 350, errorRate: 0.9, requestCount: 987 },
                { endpoint: '/api/palm/reading', avgResponseTime: 320, errorRate: 0.6, requestCount: 876 }
            ],
            performanceTrend: [
                { time: '00:00', avgResponseTime: 150 },
                { time: '04:00', avgResponseTime: 120 },
                { time: '08:00', avgResponseTime: 160 },
                { time: '12:00', avgResponseTime: 200 },
                { time: '16:00', avgResponseTime: 190 },
                { time: '20:00', avgResponseTime: 220 },
                { time: '23:59', avgResponseTime: 180 }
            ],
            errorCount: {
                total: 45,
                byCode: [
                    { code: 400, count: 12 },
                    { code: 401, count: 8 },
                    { code: 404, count: 15 },
                    { code: 500, count: 10 }
                ]
            }
        };
        
        res.status(200).json({
            success: true,
            data: performanceData,
            message: '获取API性能统计成功'
        });
    } catch (error) {
        logger.error('获取API性能统计失败', error);
        res.status(500).json({
            success: false,
            message: '获取API性能统计失败',
            error: error.message
        });
    }
}

/**
 * 获取用户行为分析数据
 */
async function getUserBehaviorStats(req, res) {
    try {
        logger.info('获取用户行为分析数据');
        
        // 模拟用户行为数据
        const behaviorData = {
            sessionStats: {
                avgSessionDuration: 4.5, // 平均会话时长（分钟）
                avgPagesPerSession: 3.2,
                bounceRate: 25.4 // 跳出率（百分比）
            },
            featureUsage: [
                { feature: '每日运势', usage: 85 },
                { feature: '塔罗牌占卜', usage: 65 },
                { feature: '周公解梦', usage: 55 },
                { feature: '面相分析', usage: 40 },
                { feature: '手相解读', usage: 35 }
            ],
            retentionRate: [
                { period: '次日', rate: 65 },
                { period: '7天', rate: 45 },
                { period: '30天', rate: 25 }
            ],
            deviceStats: [
                { device: '手机', percentage: 75 },
                { device: '平板', percentage: 15 },
                { device: '桌面', percentage: 10 }
            ]
        };
        
        res.status(200).json({
            success: true,
            data: behaviorData,
            message: '获取用户行为分析成功'
        });
    } catch (error) {
        logger.error('获取用户行为分析失败', error);
        res.status(500).json({
            success: false,
            message: '获取用户行为分析失败',
            error: error.message
        });
    }
}

/**
 * 获取系统健康状态数据
 */
async function getSystemHealthStats(req, res) {
    try {
        logger.info('获取系统健康状态数据');
        
        // 获取当前内存使用情况
        const memoryUsage = process.memoryUsage();
        
        // 模拟系统健康数据
        const healthData = {
            uptime: Math.floor(process.uptime() / 3600), // 运行时间（小时）
            memoryUsage: {
                rss: Math.round(memoryUsage.rss / (1024 * 1024)), // 内存使用量（MB）
                heapTotal: Math.round(memoryUsage.heapTotal / (1024 * 1024)),
                heapUsed: Math.round(memoryUsage.heapUsed / (1024 * 1024))
            },
            processCount: 1,
            databaseConnections: 15,
            apiServerStatus: 'online',
            databaseStatus: 'online',
            lastMaintenance: '2024-04-20T10:00:00Z',
            alertCount: 2
        };
        
        res.status(200).json({
            success: true,
            data: healthData,
            message: '获取系统健康状态成功'
        });
    } catch (error) {
        logger.error('获取系统健康状态失败', error);
        res.status(500).json({
            success: false,
            message: '获取系统健康状态失败',
            error: error.message
        });
    }
}

module.exports = {
    getOverviewStats,
    getUserGrowthStats,
    getContentUsageStats,
    getApiPerformanceStats,
    getUserBehaviorStats,
    getSystemHealthStats
};